/**
 * 
 */
package cn.biplam.front.page;

import java.io.PrintWriter;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.biplam.common.tools.DEBUG;
import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.common.wrapper.KvMap;
import cn.biplam.common.wrapper.UserInfo;

/**
 * 页面响应类基础类
 * @author 	WangSong 2009-11-16 上午10:18:30
 * @version 1.0
 */
public abstract class Page {
	
	protected HttpServletRequest request=null;
	protected HttpServletResponse response=null;
	protected String sHomeUrl;
	protected UserInfo mUser;

	/**
	 * 传入Http页面句柄初始化
	 * @param request	HttpServletRequest
	 * @param response	HttpServletResponse
	 */
	public Page(HttpServletRequest request, HttpServletResponse response){
		this.request=request;
		this.response=response;
		this.sHomeUrl=request.getContextPath();
		try {
			this.mUser=LoginDo.isLogin(request, response);
		} catch (ErrorMessage e) {
			DEBUG.println("【系统异常】");
			e.printStackTrace();
		}
	}

	/**
	 * Index调用接口方法,负责向response写入http文本
	 * @throws ErrorMessage
	 */
	public void draw() throws ErrorMessage{
		try {
			this.response.setContentType("text/html"); 
			PrintWriter out = new PrintWriter (this.response.getOutputStream());
			out.print(this._draw());
			out.close();
		} catch(ErrorMessage e){
			throw e;
		} catch (Exception e) {
			throw new ErrorMessage(e,"未知的页面请求错误(Page)!");
		}
	}
	
	/**
	 * 实现类http文本返回
	 * @return String
	 * @throws ErrorMessage
	 */
	protected abstract String _draw() throws ErrorMessage;
	
	/**
	 * 如果需要解析页面请求中的参数集合，调用本方法，获取params
	 * @return KvMap<String, String>
	 * @throws ErrorMessage
	 */
	protected KvMap<String, String> getParams() throws ErrorMessage{
		KvMap<String, String> params=new KvMap<String, String>();
		Iterator<?> ite=request.getParameterMap().keySet().iterator();
		String key=null;
		while(ite.hasNext()){
			key=ite.next().toString();
			params.put(key, request.getParameter(key));
		}
		return params;
	}
}
